package com.zhc.dejingapi.utils;

import com.bstek.ureport.export.ExportConfigureImpl;
import com.bstek.ureport.export.ExportManager;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Objects;
/**
 导出excel、pdf
 */
public class ExportUtils {
    public static void exportPdf(ExportManager exportManager, String sourcePath, String targetPath, Map<String, Object> param) throws Exception {
        try {
            OutputStream fos = new FileOutputStream(targetPath);
            try {
                ExportConfigureImpl exportConfigure = new ExportConfigureImpl(sourcePath, param, fos);
                exportManager.exportPdf(exportConfigure);
            } catch (Exception e) {
                throw new Exception("exportPdf error", e);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    }catch(Exception e) {
                        throw new Exception("exportPdf error", e);
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception("exportPdf error", e);
        }
    }
    public static void exportExcel(ExportManager exportManager, String sourcePath, String targetPath, Map<String, Object> param) throws Exception {
        try {
            OutputStream fos = new FileOutputStream(targetPath);
            try {
                String ext = targetPath.substring(targetPath.indexOf(".") + 1);
                ExportConfigureImpl exportConfigure = new ExportConfigureImpl(sourcePath, param, fos);
                if (Objects.equals(ext, "xls")) {
                    exportManager.exportExcel97(exportConfigure);
                } else {
                    if (!Objects.equals(ext, "xlsx")) {
                        throw new Exception("File name is not support!");
                    }
                    exportManager.exportExcel(exportConfigure);
                }
            } catch (Exception e) {
                throw new Exception("exportExcel error", e);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (Exception e) {
                        throw new Exception("exportExcel error", e);
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception("exportExcel error", e);
        }
    }

}